#include "exhibitionwidget.h"
#include "ui_exhibitionwidget.h"
#include "databasemanager.h"
#include "eventdetaildialog.h"

#include <QGridLayout>
#include <QLabel>
#include <QPushButton>
#include <QSignalMapper>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QMessageBox>

exhibitionwidget::exhibitionwidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::exhibitionwidget)
{
    ui->setupUi(this);



    // 确保scrollAreaWidgetContents的布局是QGridLayout
    if (!qobject_cast<QGridLayout*>(ui->scrollAreaWidgetContents->layout())) {
        QGridLayout *gridLayout = new QGridLayout(ui->scrollAreaWidgetContents);
        ui->scrollAreaWidgetContents->setLayout(gridLayout);
    }

    // 连接搜索框文本变化信号
    connect(ui->lineEditSearch, &QLineEdit::textChanged,
            this, &exhibitionwidget::on_lineEditSearch_textChanged);

    loadEvents();  // 默认加载全部活动
}

exhibitionwidget::~exhibitionwidget()
{
    delete ui;
}

// 搜索框文本变化时调用
void exhibitionwidget::on_lineEditSearch_textChanged(const QString &text)
{
     loadEvents(text.trimmed());
}

// 加载活动列表，filter为空则加载全部，否则模糊匹配名称
void exhibitionwidget::loadEvents(const QString &filter)
{
    QGridLayout *layout = qobject_cast<QGridLayout*>(ui->scrollAreaWidgetContents->layout());
    if (!layout) {
        qDebug() << "没有找到GridLayout";
        return;
    }

    // 清理旧卡片
    while (QLayoutItem *item = layout->takeAt(0)) {
        if (item->widget())
            item->widget()->deleteLater();
        delete item;
    }

    QSqlQuery query(DatabaseManager::instance().getDatabase());

    if (filter.isEmpty()) {
        if (!query.exec("SELECT event_id, name, type, start_date, end_date, description, ticket_required "
                        "FROM Exhibitions_Events ORDER BY start_date DESC")) {
            qDebug() << "查询活动失败:" << query.lastError().text();
            return;
        }
    } else {
        query.prepare("SELECT event_id, name, type, start_date, end_date, description, ticket_required "
                      "FROM Exhibitions_Events WHERE name LIKE :filter ORDER BY start_date DESC");
        query.bindValue(":filter", "%" + filter + "%");
        if (!query.exec()) {
            qDebug() << "模糊查询活动失败:" << query.lastError().text();
            return;
        }
    }

    int row = 0, col = 0;
    const int maxCol = 3;

    while (query.next()) {
        int eventId = query.value("event_id").toInt();
        QString name = query.value("name").toString();
        QString type = query.value("type").toString();
        QString startDate = query.value("start_date").toString();
        QString endDate = query.value("end_date").toString();
        QString description = query.value("description").toString();
        bool ticketRequired = query.value("ticket_required").toBool();

        QWidget *card = createEventCard(eventId, name, type, startDate, endDate, description, ticketRequired);
        layout->addWidget(card, row, col);

        col++;
        if (col >= maxCol) {
            col = 0;
            row++;
        }
    }
}

QWidget* exhibitionwidget::createEventCard(int eventId,
                                           const QString &name,
                                           const QString &type,
                                           const QString &startDate,
                                           const QString &endDate,
                                           const QString &description,
                                           bool ticketRequired)
{
    QWidget *card = new QWidget;
    QHBoxLayout *hLayout = new QHBoxLayout(card);

    QLabel *titleLabel = new QLabel(name, card);
    QPushButton *detailButton = new QPushButton("详情", card);

    detailButton->setStyleSheet(R"(
        QPushButton {
            background-color: #3498db;  /* 初始蓝色 */
            color: white;               /* 字体白色 */
            font-weight: bold;         /* 加粗字体 */
            border: none;
            border-radius: 6px;
            padding: 6px 12px;
        }
        QPushButton:hover {
            background-color: #2c80b4;  /* 悬停时变深蓝 */
        }
    )");

    hLayout->addWidget(titleLabel);
    hLayout->addStretch();
    hLayout->addWidget(detailButton);

    // 信号映射，将按钮点击映射为eventId
    QSignalMapper *mapper = new QSignalMapper(card);
    connect(detailButton, SIGNAL(clicked()), mapper, SLOT(map()));
    mapper->setMapping(detailButton, eventId);
    connect(mapper, SIGNAL(mapped(int)), this, SLOT(handleDetailButtonClick(int)));

    return card;
}

void exhibitionwidget::handleDetailButtonClick(int eventId)
{
    QSqlQuery query(DatabaseManager::instance().getDatabase());
    query.prepare("SELECT name, type, start_date, end_date, description, ticket_required FROM Exhibitions_Events WHERE event_id = :id");
    query.bindValue(":id", eventId);
    if (!query.exec() || !query.next()) {
        QMessageBox::warning(this, "错误", "未找到活动详细信息！");
        return;
    }

    QString name = query.value("name").toString();
    QString type = query.value("type").toString();
    QString startDate = query.value("start_date").toString();
    QString endDate = query.value("end_date").toString();
    QString description = query.value("description").toString();
    bool ticketRequired = query.value("ticket_required").toBool();

    eventdetaildialog dlg(eventId, name, type, startDate, endDate, description, ticketRequired, this);
    dlg.exec();
}
